package com.example.administrator.baikangxing.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.administrator.baikangxing.Dao.OperateData;
import com.example.administrator.baikangxing.MyApplication;
import com.example.administrator.baikangxing.R;
import com.example.administrator.baikangxing.config.Constants;
import com.example.administrator.baikangxing.config.Url;
import com.example.administrator.baikangxing.utils.HttpUtil;
import com.example.administrator.baikangxing.utils.LogUtil;
import com.example.administrator.baikangxing.utils.ProgressDialogUtils;
import com.example.administrator.baikangxing.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import static com.example.administrator.baikangxing.MyApplication.activitys;


public class LoginActivity extends FragmentActivity implements View.OnClickListener {

    private EditText login_et_username;
    private EditText login_et_password;
    private TextView login_tv_login;
    private TextView login_tv_reg;
    private TextView login_tv_forget;
    private ImageView login_iv_weixin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);  //去掉标题栏
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);//防止软件盘弹出,使界面变形
        setContentView(R.layout.activity_login);
        activitys.add(LoginActivity.this);
        setTab();
        initView();
    }

    private void initView() {
        login_et_username = (EditText) findViewById(R.id.login_et_username);
        login_et_password = (EditText) findViewById(R.id.login_et_password);
        login_tv_login = (TextView) findViewById(R.id.login_tv_login);
        login_tv_reg = (TextView) findViewById(R.id.login_tv_reg);
        login_tv_forget = (TextView) findViewById(R.id.login_tv_forget);
        login_iv_weixin = (ImageView) findViewById(R.id.login_iv_weixin);
        login_tv_login.setOnClickListener(this);
        login_tv_forget.setOnClickListener(this);
        login_iv_weixin.setOnClickListener(this);
        login_tv_reg.setOnClickListener(this);
    }

    private void setTab() {
        //透明状态栏  
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            // Translucent status bar  
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_tv_login://点击登录
                final String username = login_et_username.getText().toString().trim();
                String password = login_et_password.getText().toString().trim();
                if (username == null || "".equals(username)) {
                    ToastUtil.showToast(getString(R.string.login_username_hint));
                } else if (password == null || "".equals(password)) {
                    ToastUtil.showToast(getString(R.string.login_password_hint));
                } else {
                    final ProgressDialog dialog = ProgressDialogUtils.createProgressDialog(this, "正在登录");
                    dialog.show();
                    /*请求网络进行登录*/
                    String[] values = new String[]{username, password,"str","logintype","key","ext"};
                    HttpUtil.getInstance().postLoginString(Url.login_url, new String[]{"user", "password","str","logintype","key","ext"}, values, new HttpUtil.CallBackPostString() {
                        @Override
                        public void onSuccess(JSONObject successString) {
                            try {
                                String errorCode = successString.getString("errorCode");
                                if(errorCode.equals("0") ){//登录成功
                                    dialog.dismiss();
                                    JSONObject message = successString.getJSONObject("message");
                                    //保存Token
                                    OperateData.saveStringData(MyApplication.context, Constants.APP_TOKEN, message.getString("token"));
                                    //保存用户名
                                    OperateData.saveStringData(MyApplication.context, Constants.USER_NAME, username);
                                    /*保存用户头像*/
                                    OperateData.saveStringData(MyApplication.context,Constants.USER_IMAGE,message.getString("userimgurl"));
                                    /*保存用户nickname*/
                                    OperateData.saveStringData(MyApplication.context,Constants.USER_NICKNAME,message.getString("nickname"));
                                    ToastUtil.showToast("登录成功");
                                    LogUtil.e("系统登录的帐号为:"+OperateData.getStringData(MyApplication.context,Constants.USER_NAME));
                                    OperateData.saveIntData(MyApplication.context,Constants.USER_STATE,1);
                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                }else if(errorCode.equals("9")){//登录失败
                                    dialog.dismiss();
                                    ToastUtil.showToast("您输入的帐号不存在，请重新输入");
                                }else if(errorCode.equals("10")){
                                    ToastUtil.showToast("用户名或密码错误，请重新输入");
                                }else {
                                    ToastUtil.showToast(successString.getString("errorInfo"));

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFail(JSONObject failString) {
                            ToastUtil.showToast("网络连接失败");
                            dialog.dismiss();
                        }

                        @Override
                        public void onProgress(long bytesWritten, long totalSize) {
                            int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
                            dialog.setMax(100);
                            dialog.setProgress(count);
                            dialog.show();
                        }
                    });
                }
                break;
            case R.id.login_tv_reg://注册用户
                Intent intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.login_tv_forget://忘记密码
                Intent intent1 = new Intent(this, ForgotActivity.class);
                startActivity(intent1);
                break;
            case R.id.login_iv_weixin://微信登录

                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            MyApplication.getInstance().destory();
        }
        return false;
    }
}
